package com.guducat.collegeWeb.config;

import cn.dev33.satoken.stp.StpInterface;
import com.guducat.collegeWeb.entity.Permission;
import com.guducat.collegeWeb.entity.User;
import com.guducat.collegeWeb.mapper.PermissionMapper;
import com.guducat.collegeWeb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    private final PermissionMapper permissionMapper;
    private final UserMapper userMapper;

    @Autowired
    public StpInterfaceImpl(PermissionMapper permissionMapper, UserMapper userMapper) {
        this.permissionMapper = permissionMapper;
        this.userMapper = userMapper;
    }

    /**
     * 返回一个账号所拥有的权限码集合
     * @param loginId 登录ID
     * @param loginType 登录类型
     * @return 权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 获取用户ID
        Integer userId = Integer.parseInt(loginId.toString());

        // 查询用户
        User user = userMapper.findById(userId);
        if (user == null || user.getPermission() == null || user.getPermission().isEmpty()) {
            return new ArrayList<>();
        }

        // 解析权限ID列表
        String[] permissionIds = user.getPermission().split(",");
        List<String> permissionList = new ArrayList<>();

        // 查询权限详情
        for (String permissionId : permissionIds) {
            try {
                Integer id = Integer.parseInt(permissionId.trim());
                Permission permission = permissionMapper.getPermissionById(id);
                if (permission != null) {
                    permissionList.add(permission.getName());
                }
            } catch (NumberFormatException e) {
                // 忽略无效的权限ID
            }
        }

        return permissionList;
    }

    /**
     * 返回一个账号所拥有的角色标识集合
     * @param loginId 登录ID
     * @param loginType 登录类型
     * @return 角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 本项目暂不使用角色，返回空集合
        return new ArrayList<>();
    }
}
